package com.seu.vcampus.view.library;

import com.seu.vcampus.client.VCampusClient;
import com.seu.vcampus.message.Message;
import com.seu.vcampus.util.UIStyleUtil;
import com.seu.vcampus.vo.Book;
import com.seu.vcampus.vo.BorrowRecord;
import com.seu.vcampus.vo.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * 现代化图书馆管理面板
 * 采用Material Design设计风格
 * 
 * @author 虚拟校园开发团队
 * @since 1.0.0
 */
public class ModernLibraryPanel extends JPanel {
    private VCampusClient client;
    private User currentUser;
    
    // 表格组件
    private JTable bookTable;
    private DefaultTableModel bookTableModel;
    private JTable borrowTable;
    private DefaultTableModel borrowTableModel;
    
    // 搜索组件
    private JTextField searchField;
    private JButton searchButton;
    private JButton clearButton;
    
    // 操作按钮
    private JButton addBookButton;
    private JButton editBookButton;
    private JButton deleteBookButton;
    private JButton refreshButton;
    private JButton exportButton;
    
    // 状态标签
    private JLabel statusLabel;
    private JLabel bookCountLabel;
    private JLabel borrowCountLabel;
    
    public ModernLibraryPanel(VCampusClient client, User user) {
        this.client = client;
        this.currentUser = user;
        
        UIStyleUtil.setupGlobalStyle();
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        loadInitialData();
    }
    
    /**
     * 初始化所有组件
     */
    private void initializeComponents() {
        setLayout(new BorderLayout());
        setBackground(UIStyleUtil.BACKGROUND_COLOR);
        setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 初始化表格
        setupTables();
        
        // 初始化搜索组件
        searchField = UIStyleUtil.createModernTextField("搜索书名、作者、ISBN...");
        searchButton = UIStyleUtil.createPrimaryButton("搜索");
        clearButton = UIStyleUtil.createSecondaryButton("清空");
        
        // 初始化操作按钮
        addBookButton = UIStyleUtil.createSuccessButton("添加图书");
        editBookButton = UIStyleUtil.createWarningButton("编辑图书");
        deleteBookButton = UIStyleUtil.createDangerButton("删除图书");
        refreshButton = UIStyleUtil.createSecondaryButton("刷新");
        exportButton = UIStyleUtil.createSecondaryButton("导出");
        
        // 初始化状态标签
        statusLabel = UIStyleUtil.createModernLabel("就绪", UIStyleUtil.BODY_FONT, UIStyleUtil.SECONDARY_COLOR);
        bookCountLabel = UIStyleUtil.createModernLabel("图书: 0", UIStyleUtil.BODY_FONT, UIStyleUtil.PRIMARY_COLOR);
        borrowCountLabel = UIStyleUtil.createModernLabel("借阅记录: 0", UIStyleUtil.BODY_FONT, UIStyleUtil.PRIMARY_COLOR);
    }
    
    /**
     * 设置表格组件
     */
    private void setupTables() {
        // 图书表格
        String[] bookColumns = {"图书ID", "书名", "作者", "出版社", "ISBN", "库存", "状态", "操作"};
        bookTableModel = new DefaultTableModel(bookColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 7; // 只有操作列可编辑
            }
        };
        bookTable = new JTable(bookTableModel);
        bookTable.setFont(UIStyleUtil.BODY_FONT);
        bookTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        bookTable.getTableHeader().setBackground(UIStyleUtil.LIGHT_COLOR);
        bookTable.getTableHeader().setForeground(UIStyleUtil.DARK_COLOR);
        bookTable.setRowHeight(35);
        bookTable.setGridColor(UIStyleUtil.BORDER_COLOR);
        bookTable.setSelectionBackground(new Color(66, 133, 244, 50));
        bookTable.setSelectionForeground(UIStyleUtil.DARK_COLOR);
        
        // 借阅记录表格
        String[] borrowColumns = {"记录ID", "用户ID", "图书ID", "书名", "借阅日期", "应还日期", "归还日期", "状态"};
        borrowTableModel = new DefaultTableModel(borrowColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        borrowTable = new JTable(borrowTableModel);
        borrowTable.setFont(UIStyleUtil.BODY_FONT);
        borrowTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        borrowTable.getTableHeader().setBackground(UIStyleUtil.LIGHT_COLOR);
        borrowTable.getTableHeader().setForeground(UIStyleUtil.DARK_COLOR);
        borrowTable.setRowHeight(35);
        borrowTable.setGridColor(UIStyleUtil.BORDER_COLOR);
        borrowTable.setSelectionBackground(new Color(66, 133, 244, 50));
        borrowTable.setSelectionForeground(UIStyleUtil.DARK_COLOR);
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(15, 15));
        mainPanel.setBackground(UIStyleUtil.BACKGROUND_COLOR);
        
        // 顶部搜索面板
        JPanel searchPanel = createSearchPanel();
        
        // 中部内容面板
        JPanel contentPanel = createContentPanel();
        
        // 底部状态面板
        JPanel statusPanel = createStatusPanel();
        
        mainPanel.add(searchPanel, BorderLayout.NORTH);
        mainPanel.add(contentPanel, BorderLayout.CENTER);
        mainPanel.add(statusPanel, BorderLayout.SOUTH);
        
        add(mainPanel);
    }
    
    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel searchPanel = UIStyleUtil.createCardPanel("搜索与操作");
        searchPanel.setLayout(new BorderLayout(15, 15));
        
        // 搜索区域
        JPanel searchArea = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        searchArea.setOpaque(false);
        searchArea.add(new JLabel("搜索:"));
        searchArea.add(searchField);
        searchArea.add(searchButton);
        searchArea.add(clearButton);
        
        // 操作区域
        JPanel actionArea = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        actionArea.setOpaque(false);
        actionArea.add(addBookButton);
        actionArea.add(editBookButton);
        actionArea.add(deleteBookButton);
        actionArea.add(refreshButton);
        actionArea.add(exportButton);
        
        searchPanel.add(searchArea, BorderLayout.WEST);
        searchPanel.add(actionArea, BorderLayout.EAST);
        
        return searchPanel;
    }
    
    /**
     * 创建内容面板
     */
    private JPanel createContentPanel() {
        JPanel contentPanel = new JPanel(new GridLayout(2, 1, 15, 15));
        contentPanel.setOpaque(false);
        
        // 图书表格面板
        JPanel bookPanel = UIStyleUtil.createCardPanel("图书管理");
        bookPanel.setLayout(new BorderLayout());
        
        JScrollPane bookScrollPane = UIStyleUtil.createModernScrollPane(bookTable);
        bookScrollPane.setPreferredSize(new Dimension(800, 350)); // 增大表格尺寸
        bookPanel.add(bookScrollPane, BorderLayout.CENTER);
        
        // 借阅记录表格面板
        JPanel borrowPanel = UIStyleUtil.createCardPanel("借阅记录管理");
        borrowPanel.setLayout(new BorderLayout());
        
        JScrollPane borrowScrollPane = UIStyleUtil.createModernScrollPane(borrowTable);
        borrowScrollPane.setPreferredSize(new Dimension(800, 350)); // 增大表格尺寸
        borrowPanel.add(borrowScrollPane, BorderLayout.CENTER);
        
        contentPanel.add(bookPanel);
        contentPanel.add(borrowPanel);
        
        return contentPanel;
    }
    
    /**
     * 创建状态面板
     */
    private JPanel createStatusPanel() {
        JPanel statusPanel = new JPanel(new BorderLayout());
        statusPanel.setOpaque(false);
        statusPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        
        JPanel leftStatus = new JPanel(new FlowLayout(FlowLayout.LEFT));
        leftStatus.setOpaque(false);
        leftStatus.add(statusLabel);
        
        JPanel rightStatus = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        rightStatus.setOpaque(false);
        rightStatus.add(bookCountLabel);
        rightStatus.add(Box.createHorizontalStrut(20));
        rightStatus.add(borrowCountLabel);
        
        statusPanel.add(leftStatus, BorderLayout.WEST);
        statusPanel.add(rightStatus, BorderLayout.EAST);
        
        return statusPanel;
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 搜索功能
        searchButton.addActionListener(e -> performSearch());
        clearButton.addActionListener(e -> clearSearch());
        
        // 回车键搜索
        searchField.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    performSearch();
                }
            }
        });
        
        // 按钮事件
        addBookButton.addActionListener(e -> showAddBookDialog());
        editBookButton.addActionListener(e -> showEditBookDialog());
        deleteBookButton.addActionListener(e -> deleteSelectedBook());
        refreshButton.addActionListener(e -> refreshData());
        exportButton.addActionListener(e -> exportData());
    }
    
    /**
     * 加载初始数据
     */
    private void loadInitialData() {
        refreshData();
    }
    
    /**
     * 刷新数据
     */
    private void refreshData() {
        statusLabel.setText("正在加载数据...");
        
        new Thread(() -> {
            try {
                loadBooks();
                loadBorrowRecords();
                
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("数据加载完成");
                    updateStatusCounts();
                });
            } catch (Exception e) {
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("数据加载失败: " + e.getMessage());
                    JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), 
                                                 "错误", JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }
    
    /**
     * 加载图书数据
     */
    private void loadBooks() throws Exception {
        Message request = new Message(Message.Type.GET_BOOKS_REQUEST);
        Message response = client.sendMessage(request);
        
        if (response.getType() == Message.Type.GET_BOOKS_RESPONSE) {
            List<?> payload = (List<?>) response.getPayload();
            List<Book> books = new ArrayList<>();
            for (Object obj : payload) {
                if (obj instanceof Book) {
                    books.add((Book) obj);
                }
            }
            
            SwingUtilities.invokeLater(() -> updateBookTable(books));
        }
    }
    
    /**
     * 加载借阅记录
     */
    private void loadBorrowRecords() throws Exception {
        statusLabel.setText("正在加载借阅记录...");
        
        new Thread(() -> {
            try {
                Message request = new Message(Message.Type.GET_BORROW_RECORDS_REQUEST);
                request.setPayload(currentUser.getUserId());
                Message response = client.sendMessage(request);
                
                if (response.isSuccess()) {
                    List<?> payload = (List<?>) response.getPayload();
                    List<BorrowRecord> records = new ArrayList<>();
                    for (Object obj : payload) {
                        if (obj instanceof BorrowRecord) {
                            records.add((BorrowRecord) obj);
                        }
                    }
                    
                    SwingUtilities.invokeLater(() -> {
                        updateBorrowTable(records);
                        statusLabel.setText("借阅记录加载完成");
                    });
                } else {
                    SwingUtilities.invokeLater(() -> {
                        statusLabel.setText("加载借阅记录失败: " + response.getErrorMessage());
                        JOptionPane.showMessageDialog(this, 
                            "加载借阅记录失败: " + response.getErrorMessage(), 
                            "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
            } catch (Exception e) {
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("加载借阅记录失败: " + e.getMessage());
                    JOptionPane.showMessageDialog(this, 
                        "加载借阅记录失败: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }
    
    /**
     * 执行搜索
     */
    private void performSearch() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            refreshData();
            return;
        }
        
        statusLabel.setText("正在搜索...");
        
        new Thread(() -> {
            try {
                Message request = new Message(Message.Type.SEARCH_BOOKS_REQUEST);
                request.setPayload(keyword);
                Message response = client.sendMessage(request);
                
                if (response.getType() == Message.Type.SEARCH_BOOKS_RESPONSE) {
                    List<?> payload = (List<?>) response.getPayload();
                    List<Book> books = new ArrayList<>();
                    for (Object obj : payload) {
                        if (obj instanceof Book) {
                            books.add((Book) obj);
                        }
                    }
                    
                    SwingUtilities.invokeLater(() -> {
                        updateBookTable(books);
                        statusLabel.setText("搜索完成，找到 " + books.size() + " 本图书");
                    });
                }
            } catch (Exception e) {
                SwingUtilities.invokeLater(() -> {
                    statusLabel.setText("搜索失败: " + e.getMessage());
                    JOptionPane.showMessageDialog(this, "搜索失败: " + e.getMessage(), 
                                                 "错误", JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }
    
    /**
     * 清空搜索
     */
    private void clearSearch() {
        searchField.setText("");
        refreshData();
    }
    
    /**
     * 更新图书表格
     */
    private void updateBookTable(List<Book> books) {
        bookTableModel.setRowCount(0);
        for (Book book : books) {
            Object[] row = {
                book.getBookId(),
                book.getTitle(),
                book.getAuthor(),
                book.getPublisher(),
                book.getIsbn(),
                book.getStock(),
                book.getStock() > 0 ? "可借" : "已借完",
                "操作"
            };
            bookTableModel.addRow(row);
        }
        updateStatusCounts();
    }
    
    /**
     * 更新借阅记录表格
     */
    private void updateBorrowTable(List<BorrowRecord> records) {
        borrowTableModel.setRowCount(0);
        for (BorrowRecord record : records) {
            Object[] row = {
                record.getRecordId(),
                record.getUserId(),
                record.getBookId(),
                record.getBookName(),
                record.getBorrowDate(),
                record.getDueDate(),
                record.getReturnDate() != null ? record.getReturnDate() : "-",
                record.getReturnDate() == null ? "借阅中" : "已归还"
            };
            borrowTableModel.addRow(row);
        }
        updateStatusCounts();
    }
    
    /**
     * 更新状态计数
     */
    private void updateStatusCounts() {
        bookCountLabel.setText("图书: " + bookTableModel.getRowCount());
        borrowCountLabel.setText("借阅记录: " + borrowTableModel.getRowCount());
    }
    
    /**
     * 显示添加图书对话框
     */
    private void showAddBookDialog() {
        JDialog dialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(this), "添加图书", true);
        dialog.setLayout(new BorderLayout());
        
        // 创建添加图书面板
        AddBookPanel addBookPanel = new AddBookPanel(client);
        
        // 添加完成监听器
        addBookPanel.setOnBookAddedListener(() -> {
            dialog.dispose();
            refreshData();
        });
        
        dialog.add(addBookPanel, BorderLayout.CENTER);
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    /**
     * 显示编辑图书对话框
     */
    private void showEditBookDialog() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要编辑的图书", 
                                        "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String bookId = bookTableModel.getValueAt(selectedRow, 0).toString();
        String bookName = bookTableModel.getValueAt(selectedRow, 1).toString();
        String author = bookTableModel.getValueAt(selectedRow, 2).toString();
        String publisher = bookTableModel.getValueAt(selectedRow, 3).toString();
        String isbn = bookTableModel.getValueAt(selectedRow, 4).toString();
        int stock = Integer.parseInt(bookTableModel.getValueAt(selectedRow, 5).toString());

        JDialog dialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(this), "编辑图书 - " + bookName, true);
        dialog.setLayout(new BorderLayout());
        
        // 创建编辑图书面板
        EditBookPanel editBookPanel = new EditBookPanel(client, bookId, bookName, author, publisher, isbn, stock);
        
        // 添加完成监听器
        editBookPanel.setOnBookUpdatedListener(() -> {
            dialog.dispose();
            refreshData();
        });
        
        dialog.add(editBookPanel, BorderLayout.CENTER);
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    /**
     * 删除选中的图书
     */
    private void deleteSelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的图书", 
                                        "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String bookId = bookTableModel.getValueAt(selectedRow, 0).toString();
        String bookName = bookTableModel.getValueAt(selectedRow, 1).toString();

        int confirm = UIStyleUtil.showModernConfirmDialog(this, 
            "确定要删除图书《" + bookName + "》吗？", "删除确认");

        if (confirm == JOptionPane.YES_OPTION) {
            new Thread(() -> {
                try {
                    statusLabel.setText("正在删除图书...");
                    
                    Message request = new Message(Message.Type.DELETE_BOOK_REQUEST);
                    request.setPayload(bookId);
                    
                    Message response = client.sendMessage(request);
                    
                    if (response.getType() == Message.Type.DELETE_BOOK_RESPONSE) {
                        String result = (String) response.getPayload();
                        SwingUtilities.invokeLater(() -> {
                            if ("SUCCESS".equals(result)) {
                                JOptionPane.showMessageDialog(this, 
                                    "图书《" + bookName + "》删除成功", 
                                    "成功", JOptionPane.INFORMATION_MESSAGE);
                                refreshData();
                            } else {
                                JOptionPane.showMessageDialog(this, 
                                    "删除失败：" + result, 
                                    "错误", JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                } catch (Exception e) {
                    SwingUtilities.invokeLater(() -> {
                        statusLabel.setText("删除失败: " + e.getMessage());
                        JOptionPane.showMessageDialog(this, 
                            "删除失败：" + e.getMessage(), 
                            "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
            }).start();
        }
    }
    
    /**
     * 导出数据
     */
    private void exportData() {
        JOptionPane.showMessageDialog(this, "导出功能将在后续版本实现", 
                                    "提示", JOptionPane.INFORMATION_MESSAGE);
    }
}